const express = require('express');
const deployService = require('../services/deployService');
const historyService = require('../services/historyService');
const logger = require('../utils/logger');

const router = express.Router();

// 手动触发部署
router.post('/manual', async (req, res) => {
  try {
    const { branch, commit, message } = req.body;
    
    // 检查是否有部署正在进行
    const status = deployService.getStatus();
    if (status.isDeploying) {
      return res.status(409).json({
        success: false,
        message: '已有部署任务正在进行中',
        currentDeployId: status.currentDeployId
      });
    }
    
    // 创建部署记录
    const deployRecord = {
      id: Date.now().toString(),
      timestamp: new Date().toISOString(),
      branch: branch || 'main',
      commit: commit || 'manual',
      commitMessage: message || '手动触发部署',
      author: 'manual',
      status: 'pending',
      logs: [],
      isManual: true
    };
    
    await historyService.addRecord(deployRecord);
    
    // 模拟推送数据
    const mockPushData = {
      ref: `refs/heads/${deployRecord.branch}`,
      head_commit: {
        id: deployRecord.commit,
        message: deployRecord.commitMessage,
        author: { name: deployRecord.author }
      },
      repository: {
        clone_url: null // 将使用配置中的URL
      }
    };
    
    // 异步执行部署
    deployService.deploy(deployRecord.id, mockPushData)
      .then(result => {
        logger.info('手动部署完成', { deployId: deployRecord.id, success: result.success });
      })
      .catch(error => {
        logger.error('手动部署失败', { deployId: deployRecord.id, error: error.message });
      });
    
    res.json({
      success: true,
      message: '部署任务已启动',
      deployId: deployRecord.id
    });
    
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '启动部署失败',
      error: error.message
    });
  }
});

// 获取部署状态
router.get('/status', (req, res) => {
  try {
    const status = deployService.getStatus();
    res.json({
      success: true,
      data: status
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取部署状态失败',
      error: error.message
    });
  }
});

// 获取特定部署的状态
router.get('/:deployId/status', async (req, res) => {
  try {
    const { deployId } = req.params;
    const record = await historyService.getRecord(deployId);
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '部署记录不存在'
      });
    }
    
    // 只返回状态相关信息
    res.json({
      success: true,
      data: {
        id: record.id,
        status: record.status,
        startTime: record.startTime,
        endTime: record.endTime,
        updatedAt: record.updatedAt
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取部署状态失败',
      error: error.message
    });
  }
});

// 获取特定部署的详细信息
router.get('/:deployId', async (req, res) => {
  try {
    const { deployId } = req.params;
    const record = await historyService.getRecord(deployId);
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '部署记录不存在'
      });
    }
    
    res.json({
      success: true,
      data: record
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取部署信息失败',
      error: error.message
    });
  }
});

// 获取部署日志（实时）
router.get('/:deployId/logs', async (req, res) => {
  try {
    const { deployId } = req.params;
    const record = await historyService.getRecord(deployId);
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '部署记录不存在'
      });
    }
    
    res.json({
      success: true,
      data: {
        logs: record.logs || [],
        status: record.status,
        updatedAt: record.updatedAt
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取部署日志失败',
      error: error.message
    });
  }
});

// 停止当前部署（如果支持的话）
router.post('/stop', (req, res) => {
  try {
    const status = deployService.getStatus();
    
    if (!status.isDeploying) {
      return res.status(400).json({
        success: false,
        message: '当前没有正在进行的部署任务'
      });
    }
    
    // 注意：这里只是返回状态，实际的停止逻辑需要在deployService中实现
    res.json({
      success: false,
      message: '部署停止功能暂未实现',
      currentDeployId: status.currentDeployId
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '停止部署失败',
      error: error.message
    });
  }
});

module.exports = router;